# encoding:utf-8
import datetime
import json
import random
from flask import render_template, request, redirect, Blueprint, session, url_for, g, send_from_directory, current_app, \
    jsonify

from form.user import LoginForm, ProductTimeSaleSearchForm, PhoneSettingInfo
from models._base import conn
import time
from page_data import PageData
from sql.brand import SearchBrandSql
from sql.store import SearchStoreSql, ProductOrderDetailsStoreHandleSQL, IndexDataStoreHandleSQL

from sql.user import SearchUserByUserIdPwdSQL, SearchAllUserSql, SearchAllUsersStoreHandleSql, \
    InsertUserPhoneSettingSQL, UpdateUserPhoneSettingSQL, UpdateUserOpenIdSQL
from utils.account import signout_user
from utils.helper import get_url_data
from utils.permissions import require_user
from wechat import WeixinHelper

base_page = Blueprint('base_page', __name__)


@base_page.route('/login', methods=['GET', 'POST'])
def login():
    """登录"""
    form = LoginForm()
    error_info = ""
    if request.method == 'POST':
        name = request.form.get("name")
        pwd = request.form.get("pwd")
        user = PageData.user_login(**{
            "UserID": name,
            "UserPwd": pwd})
        if user:
            brand_store_info = PageData.get_user_brand_store(**{
                "UserID": name
            })
            session['brands'] = brand_store_info

            return redirect(url_for("base_page.index"))
        else:
            error_info = "账号或密码错误"

    return render_template('login.html', form=form, error_info=error_info)


@base_page.route('/logout')
def logout():
    """退出"""
    signout_user()

    return redirect(url_for('base_page.login'))


@base_page.route('/')
@require_user
def index():
    """
    首页
    从T_ReportHomePage_StStore表读取
    从T_ReportBrandFinancialDataStatisticsDetail表读取支付方式明细
    从MCCP_HD_Sale读取菜品销售
    """
    now_date = datetime.datetime.now().date()
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")
    current_brand = '全部'
    current_shop = '全部'
    shops=[]
    if 'brands' not in session:
        return redirect(url_for('base_page.login'))
    brands = session['brands']
    if len(brands.keys()) > 0:
        if not brand_id:
            brand_id = brands.keys()[0]
        if brand_id in brands:
            current_brand = brands[brand_id]['name']
            shops = brands[brand_id]['shops']
            if shop_id:
                print filter(lambda s: s['id'] == shop_id, shops)
                current_shop = filter(lambda s: s['id'] == shop_id, shops)[0]['name']
    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
    home_page_data = {
        u"主营业数据": {},
        u"实付支付情况": {},
        u"菜品销售情况": {},
        u"同业对比": {},
    }

    home_page_data[u'主营业数据'] = PageData.main_data_store_statistic(**{
        "BrandID": brand_id,
        "StoreID": shop_id
    })
    payment_total, product_payment_data = PageData.get_payment_proportion_data(**{
        "StoreID": shop_id,
        "BrandID": brand_id
    })

    # 同业对比
    test_date = now_date
    test_date = "2017-10-14"
    compare_with_lastweek_data = PageData.get_sale_compare_with_lastweek(**{
        "StoreID": shop_id,
        "DayStartTime": str(start_date) + " 00:00:00",
        "DayEndTime": str(end_date) + " 23:59:59"

    })
    lastweeek_date = now_date - datetime.timedelta(days=7)
    lastweeek_compare_with_lastweek_data = PageData.get_sale_compare_with_lastweek(**{
        "StoreID": shop_id,
        "DayStartTime": str(lastweeek_date) + " 00:00:00",
        "DayEndTime": str(lastweeek_date) + " 23:59:59"

    })

    try:
        resList = conn.ExecQuery(SearchAllUserSql)
    except Exception, e:
        print e
    users = []
    for data in resList:
        users.append({
            'id': data[0],
            'name': data[1]
        })
    conn.conn.close()

    return render_template('index.html', start_date=start_date,
                           end_date=end_date, users=users, shops=shops, brands=brands,
                           shop_id=shop_id, brand_id=brand_id, now_time=now_time,
                           current_brand=current_brand, home_page_data=home_page_data,
                            product_payment_data=json.dumps(product_payment_data),
                           payment_total=payment_total,
                           compare_with_lastweek_data=compare_with_lastweek_data,
                           lastweeek_compare_with_lastweek_data=lastweeek_compare_with_lastweek_data,
                           current_shop=current_shop,
                           now_date=now_date)


@base_page.route('/index/top')
@require_user
def top():
    """
    顶部
    """

    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")

    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
    home_page_data = {
        u"主营业数据": {},
        u"实付支付情况": {},
        u"菜品销售情况": {},
        u"同业对比": {},
    }

    return render_template('index/top.html',
                           shop_id=shop_id, brand_id=brand_id,
                           home_page_data=home_page_data,
                           )


@base_page.route('/get_top_data')
@require_user
def ajax_top_data():
    """
    顶部
    """
    now_date = datetime.datetime.now().date()
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")

    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
    home_page_data = {
        u"主营业数据": {},
        u"实付支付情况": {},
        u"菜品销售情况": {},
        u"同业对比": {},
    }
    main_data = PageData.main_data_store_statistic(**{
        "BrandID": brand_id,
        "StoreID": shop_id
    })

    return jsonify({"status": 'ok', 'data': main_data})


@base_page.route('/index/paid')
@require_user
def index_paid():
    """
    支付占比

    """
    now_date = datetime.datetime.now().date()
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")

    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))

    payment_total, product_payment_data = PageData.get_payment_proportion_data(**{
        "StoreID": shop_id,
        "BrandID": brand_id
    })
    shops = []

    # 营销日报
    day_sale_query = PageData.get_store_day_financial_data(**{
        "DateB": str(start_date),
        "DateE": str(end_date),
        "StoreID": shop_id
    })

    now_date = datetime.datetime.now().date()
    recharge_total, data_list = PageData.get_recharge_total_data(**{
        "StoreID": shop_id,
        "DayStartTime": str(now_date) + " 00:00:00",
        "DayEndTime": str(now_date) + " 23:59:59"
    })

    abnormal_total, abnormal_data_list = PageData.get_abnormal_operation_data(**{
        "StoreID": shop_id
    })
    return render_template('index/paid.html', start_date=start_date,
                           end_date=end_date,
                           shop_id=shop_id, brand_id=brand_id, now_time=now_time,
                           payment_total=payment_total, recharge_total=recharge_total,
                           abnormal_total=abnormal_total,
                           product_payment_data=json.dumps(product_payment_data),
                           day_sale_query=day_sale_query,
                           now_date=now_date)


@base_page.route('/index/product_sale')
@require_user
def index_product_sal():
    """
    首页
    从T_ReportHomePage_StStore表读取
    从T_ReportBrandFinancialDataStatisticsDetail表读取支付方式明细
    从MCCP_HD_Sale读取菜品销售
    """
    now_date = datetime.datetime.now().date()
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")

    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
    home_page_data = {
        u"主营业数据": {},
        u"实付支付情况": {},
        u"菜品销售情况": {},
        u"同业对比": {},
    }

    sale_total, category_percent, home_page_data[u'菜品销售情况'] = PageData.product_sale_data(**{
        "DateB": "2017-01-01",
        "DateE": "2017-11-01",
        "KeyWord": "全部",
        "makeSmallID": "全部",
        "BrandID": brand_id,
        "StoreID": shop_id
    })
    return render_template('index/product_sale.html', start_date=start_date,
                           end_date=end_date,
                           shop_id=shop_id, brand_id=brand_id, now_time=now_time,
                           category_percent=json.dumps(category_percent),
                           home_page_data=home_page_data,
                           sale_total=sale_total,
                           now_date=now_date)


@base_page.route('/ajax_get_product_sale_info')
@require_user
def ajax_get_product_sale_info():
    """
    首页
    从T_ReportHomePage_StStore表读取
    从T_ReportBrandFinancialDataStatisticsDetail表读取支付方式明细
    从MCCP_HD_Sale读取菜品销售
    """
    now_date = datetime.datetime.now().date()
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")
    payment_total, product_payment_data = PageData.get_payment_proportion_data(**{
        "StoreID": shop_id,
        "BrandID": brand_id
    })
    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))

    main_data = PageData.main_data_store_statistic(**{
        "BrandID": brand_id,
        "StoreID": shop_id,
    })
    sale_total, category_percent, product_sale_sort = PageData.product_sale_data(**{
        "DateB": "2017-01-01",
        "DateE": now_date,
        "KeyWord": "全部",
        "makeSmallID": "全部",
        "BrandID": brand_id,
        "StoreID": shop_id
    })
    payment_total, product_payment_data = PageData.get_payment_proportion_data(**{
        "StoreID": shop_id,
        "BrandID": brand_id
    })
    recharge_total, recharge_data_list = PageData.get_recharge_total_data(**{
        "StoreID": shop_id,
        "DayStartTime": str(now_date) + " 00:00:00",
        "DayEndTime": str(now_date) + " 23:59:59"
    })
    abnormal_total, abnormal_data_list = PageData.get_abnormal_operation_data(**{
        "StoreID": shop_id
    })

    # 时段菜品
    time_product_data = PageData.get_product_time_sale_statistics_by_time(**{
        "DateB": start_date,
        "DateE": end_date,
        "StoreID": shop_id,
        "TimeNum": 60
    })
    payment_right_html = """

        <a href="/business.html?brand_id={brand_id}&shop_id={shop_id}">
            <label>营销日报</label>

            <p>¥ 0</p>
        </a>
        <a href="/recharge.html?brand_id={brand_id}&shop_id={shop_id}">
            <label>会员充值</label>

            <p>¥ {recharge_total}</p>
        </a>
        <a href="/abnormal.html?brand_id={brand_id}&shop_id={shop_id}">
            <label>异常操作</label>

            <p>¥ {abnormal_total}</p>
        </a>

    """.format(**{
        "shop_id": shop_id,
        "brand_id":brand_id,
        "recharge_total": recharge_total,
        "abnormal_total": abnormal_total

    })
    # TODO 参数
    give_amount_total, give_product_amount = PageData.get_give_product_sale_data(**{
        "BrandID": brand_id,
        "StoreID": shop_id,
        "DayStartTime": str(now_date) + " 00:00:00",
        "DayEndTime": str(now_date) + " 23:59:59"
    })
    commission_total, commission_data_list = PageData.get_employee_commission(**{
        "StoreID": shop_id
    })
    retreat_total,retreat_data_list = PageData.get_retreat_product_data(**{
        "StoreID": shop_id
    })
    right_html = """

        <a href="/sale.html?brand_id={brand_id}&shop_id={shop_id}">
            <img src="/static/img/i3.png">
            <label>人气菜品</label>

            <p>{top_product}</p>

        </a>
        <a href="/unsalable.html?brand_id={brand_id}&shop_id={shop_id}">
            <img src="/static/img/i4.png">
            <label>滞销菜品</label>

            <p>{worst_product}</p>
        </a>
        <a href="/retreat.html">
            <img src="/static/img/i5.png">
            <label>退品情况</label>

            <p>¥ {back_money}</p>
        </a>
        <a href="/commission.html">
            <img src="/static/img/i6.png">
            <label>员工提成</label>

            <p>¥ {employee_commission}</p>
        </a>
        <a href="/give.html">
            <img src="/static/img/i7.png">
            <label>菜品赠送</label>

            <p>¥ {give_product_amount}</p>
        </a>
        <a href="/timeMenu.html" class="timeMmenu">
            <img src="/static/img/i8.png">
            <label>时段菜品</label>

            <p>{top_time_product}</p>
        </a>
    """.format(**{
        "brand_id": brand_id,
        "shop_id": shop_id,
        "top_product": product_sale_sort[0][u'菜品'] if len(product_sale_sort) > 0 else '',
        "worst_product": product_sale_sort[-1][u'菜品'] if len(product_sale_sort) > 0 else '',  # 滞销菜品
        "back_money": retreat_total,  # 退品总额
        "employee_commission": commission_total,  # 员工提成
        "give_product_amount": give_amount_total,  # 菜品赠送
        "top_time_product": time_product_data[0][u'菜品'] if len(time_product_data) > 0 else ''
    })

    return jsonify({"status": 'ok', "data": {"main_data": main_data,
                                             "product_sale": json.dumps(category_percent),
                                             "product_sale_right_html": right_html,
                                             "payment_total": payment_total,
                                             "product_payment": json.dumps(product_payment_data),
                                             "product_payment_right_html": payment_right_html}})


@base_page.route("/sale.html")
@require_user
def sale():
    """今日销售总额
    门店id，查询日期
    """
    now_date = datetime.datetime.now().date()
    date = request.args.get("date")
    brand_id = request.args.get("brand_id", "")
    shop_id = request.args.get("shop_id", "")
    current_date = datetime.datetime.now().date()
    last_week_sale_total = 999
    # TODO 销售时间
    total_sale, category_percent, data = PageData.product_sale_data(**{
        "DateB": "2017-01-01",
        "DateE": now_date,
        "KeyWord": "全部",
        "makeSmallID": "全部",
        "BrandID": brand_id,
        "StoreID": shop_id
    })

    return render_template('sale.html', category_percent=category_percent, now_date=now_date,
                           total_sale=total_sale, last_week_sale_total=last_week_sale_total,
                           data_list=data)


@base_page.route("/abnormal.html")
@require_user
def abnormal():
    """异常操作"""
    shop_id = request.args.get("shop_id","")
    now_date = datetime.datetime.now().date()
    abnormal_total, data_list = PageData.get_abnormal_operation_data(**{
        "StoreID": shop_id
    })
    print abnormal_total
    return render_template('abnormal.html', total=abnormal_total, now_date=now_date, data_list=data_list)


@base_page.route("/timeMenu.html", methods=['POST', 'GET'])
@require_user
def time_product_sale():
    """时段菜品销售"""
    now_date = datetime.datetime.now().date()

    form = ProductTimeSaleSearchForm()
    if request.method == 'POST':
        print 111
        start_date = form.date_start.data
        end_date = form.date_end.data
    else:
        start_date = now_date
        end_date = now_date
    shop_id = request.args.get("shop_id")
    time_num = request.args.get("time_num", type=int, default=30)
    data_list = PageData.get_product_time_sale_statistics_by_time(**{
        "DateB": start_date,
        "DateE": end_date,
        "StoreID": shop_id,
        "TimeNum": time_num
    })

    return render_template('timeMenu.html', form=form, data_list=data_list, time_num=time_num,
                           start_date=start_date,
                           end_date=end_date, now_date=now_date)


@base_page.route("/commission.html")
@require_user
def commission():
    """员工提成"""
    data = []
    shop_id = request.args.get("shop_id", "")
    total, data_list = PageData.get_employee_commission(**{
        "StoreID": shop_id
    })

    return render_template('commission.html', data=data_list)


@base_page.route("/retreat.html")
@require_user
def retreat():
    """退品情况"""
    data = []
    now_date = datetime.datetime.now().date()
    shop_id = request.args.get("shop_id")
    print shop_id
    retreat_total,retreat_data_list = PageData.get_retreat_product_data(**{
        "StoreID": shop_id
    })
    return render_template('retreat.html', now_date=now_date,
                           data_list=retreat_data_list)


@base_page.route("/recharge.html")
@require_user
def member_recharge():
    """
    会员充值
    包括哪个门店，日期
    """
    data = []
    now_date = datetime.datetime.now().date()
    last_week_date = now_date - datetime.timedelta(days=7)
    shop_id = request.args.get("shop_id")
    week = request.args.get("week")
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    this_week_monday = now_date - datetime.timedelta(days=now_date.weekday())
    this_week_sunday = now_date + datetime.timedelta(days=abs(6 - now_date.weekday()))

    recharge_total, data_list = PageData.get_recharge_total_data(**{
        "StoreID": shop_id,
        "DayStartTime": str(start_date) + " 00:00:00",
        "DayEndTime": str(end_date) + " 23:59:59"
    })
    last_week_recharge_total, last_week_data_list = PageData.get_recharge_total_data(**{
        "StoreID": shop_id,
        "DayStartTime": str(last_week_date) + " 00:00:00",
        "DayEndTime": str(last_week_date) + " 23:59:59"
    })

    return render_template('recharge.html', now_date=now_date, start_date=start_date,
                           end_date=end_date,
                           recharge_total=recharge_total,
                           last_week_recharge_total=last_week_recharge_total, this_week_monday=this_week_monday,
                           week=week, this_week_sunday=this_week_sunday, data_list=data_list)


@base_page.route("/paid.html")
@require_user
def today_paid():
    """今日实收款"""

    now_date = datetime.datetime.now().date()
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    shop_id = request.args.get("shop_id", "")
    brand_id = request.args.get("brand_id", "")
    week = request.args.get("week", "")
    this_week_monday = now_date - datetime.timedelta(days=now_date.weekday())
    this_week_sunday = now_date + datetime.timedelta(days=abs(6 - now_date.weekday()))

    now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))

    payment_total, data_list = PageData.get_payment_proportion_data(**{
        "StoreID": shop_id,
        "BrandID": brand_id
    })
    return render_template('paid.html', data_list=data_list, week=week, this_week_monday=this_week_monday,
                           this_week_sunday=this_week_sunday, payment_total=payment_total)


@base_page.route("/unsalable.html")
@require_user
def unsalable():
    """滞销菜品"""
    now_date = datetime.datetime.now().date()
    return render_template('unsalable.html', now_date=now_date)


@base_page.route("/business.html")
@require_user
def business():
    """营业汇总"""
    now_date = datetime.datetime.now().date()
    shop_id = request.args.get("shop_id")
    today_sale = 0
    lastweek_sale = 0
    start_date = request.args.get("start_date", now_date)
    end_date = request.args.get("end_date", now_date)
    # 营销日报
    data = PageData.get_store_day_financial_data(**{
        "DateB": start_date,
        "DateE": now_date,
        "StoreID": shop_id
    })
    return render_template('business.html', start_date=start_date, end_date=end_date,
                           data=data, today_sale=today_sale, lastweek_sale=lastweek_sale)


@base_page.route("/contrast.html")
@require_user
def contrast():
    """当日与同业对比"""
    now_date = datetime.datetime.now().date()
    shop_id = request.args.get("shop_id")
    test_date = "2017-10-14"
    today_data = PageData.get_sale_compare_with_lastweek(**{
        "StoreID": shop_id,
        "DayStartTime": str(now_date) + " 00:00:00",
        "DayEndTime": str(now_date) + " 23:59:59"

    })
    lastweeek_date = now_date - datetime.timedelta(days=7)
    lastweek_data = PageData.get_sale_compare_with_lastweek(**{
        "StoreID": shop_id,
        "DayStartTime": str(lastweeek_date) + " 00:00:00",
        "DayEndTime": str(lastweeek_date) + " 23:59:59"

    })
    return render_template('contrast.html', lastweek_data=lastweek_data, today_data=today_data)


@base_page.route("/give.html")
@require_user
def give():
    """赠送情况"""
    return render_template('give.html')


@base_page.route("/set.html", methods=['POST', 'GET'])
@require_user
def setting():
    """设置"""
    form = PhoneSettingInfo()

    user_setting = PageData.get_user_phone_setting(**{
        "UserID": session['User']['UserID']
    })
    data = {
        "YNAbnormal": 0,
        "YNVerification": 0,
        "YNLogon": 0,
        "YNBusiness": 0
    }
    if request.method == 'GET':
        if user_setting:
            form = PhoneSettingInfo(**user_setting)
    for k, v in form.data.items():
        if k in data:
            data[k] = v
    if request.method == 'POST':
        data.update({
            'UserID': session['User']['UserID']
        })
        if user_setting:

            conn.ExecNonQuery(UpdateUserPhoneSettingSQL.format(**data))
        else:
            print InsertUserPhoneSettingSQL.format(**data)
            conn.ExecNonQuery(InsertUserPhoneSettingSQL.format(**data))
        conn.conn.close()
        return redirect(url_for('base_page.setting'))
    return render_template('set.html', form=form, data=user_setting)


@base_page.route("/MP_verify_tVS6HRoLYzAMbm5y.txt")
def wechat_check():
    return send_from_directory(
        "{}".format(current_app.config.get("PROJECT_PATH")), "MP_verify_tVS6HRoLYzAMbm5y.txt", as_attachment=True)


@base_page.route("/bind_wechat", methods=['GET', 'POST'])
@require_user
def bind_wechat():
    """绑定微信"""
    openid = session.get("openid")

    code = request.args.get("code")
    if not code:
        print request.url
        return redirect(WeixinHelper.oauth2(request.url))
    else:
        print "bind"
        wechat_bind_fun(g.user, code)
    if 'openID' in session:
        user = session['User']
        if not user:
            user = bind_wechat_openid(user, openid)

        if user.openid:
            return redirect(url_for('base_page.index'))
    else:
        return redirect(url_for('base_page.bind_wechat'))


def wechat_bind_fun(user, code):
    data = json.loads(WeixinHelper.getAccessTokenByCode(code))
    access_token, openid, refresh_token = data.get("access_token"), data.get("openid"), data.get("refresh_token")

    # print openid
    if 'openid':
        # 检查是否已绑定
        if user[''] == openid:
            session['openid'] = openid
            session['access_token'] = openid
            print u'与微信用户关联的user（%s） 已开始登陆网站...' % user.name
        else:
            bind_wechat_openid(user, openid)


def bind_wechat_openid(user, openid):
    """
    绑定微信账号到用户信息
    """

    print u'binding a wechat user ...'
    print 'waiting...'
    user_json = get_user_info(get_access_token(), openid)
    if 'errcode' in user_json:
        user_json = get_user_info(get_access_token(True), openid)

    session['openid'] = openid
    conn.ExecNonQuery(UpdateUserOpenIdSQL.format(**{
        "UserID": user['UserID']}))
    return user


def get_user_info(token, openid):
    url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN' % (token, openid)
    user_json_str = get_url_data(url)
    user_json = json.loads(user_json_str)

    return user_json


def get_access_token(update=False):
    if session.get('access_token', None) and update is False:
        return session.get('access_token')
    else:
        url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' \
              % (current_app.config.get('WECHAT_APPID'), current_app.config.get('WECHAT_APPSECRET'))
        access_token = get_url_data(url)
        dict_access_token = json.loads(access_token)
        str_access_token = dict_access_token['access_token']
        session['access_token'] = str_access_token

    return str_access_token
